<template>
  <VPage class="app-container">
    <div class="flex pl-3 w-1/2 flex-col" v-loading="loadings.tree">
      <div class="card filter">
        <VGroup class="mb-2">
          <el-select class="!w-[160px]" v-model="activated" @change="change">
            <el-option
              v-for="(item, index) in genreOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-input
            v-if="activated == 'classify'"
            v-model="filterText"
            placeholder="搜索"
            clearable
          />
          <SelectDepartment
            v-model="depart_id"
            class="w-full"
            v-if="activated == 'department'"
            :multiple="true"
          ></SelectDepartment>
          <el-button type="primary" @click="search">搜索</el-button>
        </VGroup>
        <div class="pb-[8px] flex form-divider">
          <VButton type="primary" auth="/goods/basics/classify/add" @click="open"
            ><svg-icon icon-class="add_new" />新增</VButton
          >
          <VButton
            auth="/goods/basics/classify/enable"
            status="primary"
            :loading="loadings.enable"
            @click="handleStatus('enable')"
            ><svg-icon class="mr-1 base-text-color" icon-class="state_finish_enable" />
            启用</VButton
          >
          <VButton
            auth="/goods/basics/classify/disabled"
            status="warning"
            :loading="loadings.disable"
            @click="handleStatus('disable')"
          >
            <svg-icon
              class="mr-1 text-red-500"
              icon-class="state_finish_cover"
            />禁用</VButton
          >
          <VButton
            auth="/goods/basics/classify/delete"
            :loading="loadings.del"
            @click="handleDel"
            ><svg-icon class="mr-1 text-red-500" icon-class="del" />删除</VButton
          >
        </div>
        <div class="content">
          <el-tree
            ref="treeRef"
            :node-key="id"
            :data="treeData"
            :show-checkbox="multiple"
            :check-strictly="false"
            :current-node-key="!multiple ? selected : ''"
            :highlight-current="!multiple"
            :expand-on-click-node="false"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :default-checked-keys="multiple ? selected : []"
            @node-click="handleNodeClick"
            @check-change="handleCheckChange"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <span class="tree-label flex justify-start items-center text-sm"
                  ><span class="mr-4 text-center">{{ data.id }} - {{ node.label }}</span>
                  <span class="flex justify-start items-center">
                    <VAuth auth="/goods/basics/classify/edit">
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="编辑"
                        placement="top-start"
                      >
                        <svg-icon
                          class="mr-4 base-text-color"
                          @click="open(node.data)"
                          icon-class="Edit"
                        />
                      </el-tooltip>
                    </VAuth>
                    <VAuth auth="/goods/basics/classify/up">
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="上移一层"
                        placement="top-start"
                      >
                        <svg-icon
                          class="mr-4 base-text-color"
                          :loading="loadings.up"
                          @click="handleSort('up', data.id)"
                          icon-class="move up"
                        />
                      </el-tooltip>
                    </VAuth>
                    <VAuth auth="/goods/basics/classify/down">
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="下移一层"
                        placement="top-start"
                      >
                        <svg-icon
                          class="mr-4 base-text-color"
                          :loading="loadings.down"
                          @click="handleSort('down', data.id)"
                          icon-class="move down"
                        />
                      </el-tooltip>
                    </VAuth>
                    <VAuth auth="/goods/basics/classify/delete">
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="删除"
                        placement="top-start"
                      >
                        <svg-icon
                          class="mr-4"
                          @click="del(data.id)"
                          icon-class="del (1)"
                        />
                      </el-tooltip>
                    </VAuth>
                  </span>
                </span>
                <div class="w-[200px]">
                  <span
                    class="mr-2 text-[var(--base-danger-text-color)]"
                    v-if="data.status == 2"
                    >禁用</span
                  >
                  <span
                    class="mr-2 text-[var(--base-success-text-color)]"
                    v-if="data.status == 1"
                    >启用</span
                  >
                  <VButton
                    auth="/goods/basics/classify/edit"
                    type="primary"
                    link
                    @click="handleAssociatedPlatform(data)"
                    >关联平台分类</VButton
                  >
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </div>
  </VPage>
  <ComModal ref="addref" :treeData="treeData" @query="query"></ComModal>
  <AssociatedPlatform ref="AssociatedPlatformRef"></AssociatedPlatform>
</template>
<script setup name="BasicsClassify">
import {
  queryBackendClassification,
  updateStatus,
  deleteBackendClassification,
  getCategoryList,
  updateSort,
} from "./api.js";
import { toRefs, nextTick, watch, getCurrentInstance, reactive, onMounted } from "vue";
import { ElTree, ElMessage, ElMessageBox } from "element-plus";
import ComModal from "./components/ComModal.vue";
import SelectDepartment from "@/components/SelectDepartment";
import { genreOptions } from "./data.js";
import AssociatedPlatform from "./components/AssociatedPlatform.vue";

const { proxy } = getCurrentInstance();

const loadings = reactive({
  enable: false,
  disable: false,
  del: false,
});
const selectIds = ref([]);

const defaultProps = {
  children: "son",
  label: "name",
};

const data = reactive({
  activated: "classify",
  depart_id: [],
  treeData: [],
  multiple: true,
});

const { activated, treeData, depart_id, multiple } = toRefs(data);

const treeRef = ref();

const selected = ref();

const filterText = ref("");
const search = () => {
  if (activated.value == "classify") {
    proxy.$refs["treeRef"].filter(filterText.value);
  } else if (activated.value == "department") {
    getCategoryList();
  }
};

// 过滤
const filterNode = (value, data, node) => {
  if (!value) return true;
  let parentNode = node.parent,
    labels = [node.label],
    level = 1;
  while (level < node.level) {
    labels = [...labels, parentNode.label];
    parentNode = parentNode.parent;
    level++;
  }
  return labels.some((label) => label.indexOf(value) !== -1);
};

// 多选
const handleCheckChange = () => {
  selectIds.value = treeRef.value ? getSimpleCheckedNodes(treeRef.value) : [];
  // emits("change", treeRef.value ? getSimpleCheckedNodes(treeRef.value) : "");
};
// 上移/下移
const handleSort = (type, id) => {
  const data = {
    type: type,
    id: id,
  };
  type == "up" ? (loadings.up = true) : (loadings.down = true);
  updateSort(data)
    .then((res) => {
      ElMessage.success(res.message);
      getList();
    })
    .finally(() => {
      type == "up" ? (loadings.up = false) : (loadings.down = false);
    });
};

// 当前子节点全部选中只获取当前父节点与其他子节点集合
const getSimpleCheckedNodes = (store) => {
  const checkedNodes = [];
  const traverse = function (node) {
    const childNodes = node.root ? node.root.childNodes : node.childNodes;
    childNodes.forEach((child) => {
      if (child.checked) {
        checkedNodes.push(child.data.id);
      }
      if (child.indeterminate) {
        traverse(child);
      }
    });
  };
  traverse(store);
  return checkedNodes;
};

const del = (id) => {
  ElMessageBox.confirm("确认删除该分类?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "btnFalses",
  }).then(() => {
    deleteBackendClassification({ id: [id] }).then((res) => {
      getList();
      ElMessage.success(res.message);
    });
  });
};

const addref = ref();
const open = (data) => {
  nextTick(() => {
    addref.value.open(data);
  });
};

const isHandle = () => {
  return !selectIds.value.length ? ElMessage.error("请选择分类!") && false : true;
};

const handleStatus = (type, data) => {
  let form = {};
  if (data) {
    form = {
      type: type,
      id: data.id,
    };
  } else {
    if (!isHandle()) return;
    form = {
      type: type,
      id: selectIds.value,
    };
  }

  type == "enable" ? (loadings.enable = true) : (loadings.disable = true);
  updateStatus(form)
    .then((res) => {
      selectIds.value = "";
      getList();
      ElMessage.success(res.message);
    })
    .finally(() => {
      type == "enable" ? (loadings.enable = false) : (loadings.disable = false);
    });
};
// 批量删除
const handleDel = () => {
  if (!isHandle()) return;
  ElMessageBox.confirm("确认删除该分类?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loadings.del = true;
    deleteBackendClassification({ id: selectIds.value })
      .then((res) => {
        selectIds.value = "";
        getList();
        ElMessage.success(res.message);
      })
      .finally(() => {
        loadings.del = false;
      });
  });
};

const query = () => {
  getList();
};

defineExpose({ treeRef });

const change = (val) => {
  filterText.value = "";
  depart_id.value = [];
  getList();
};

const getList = () => {
  getCategoryList({
    depart_id: depart_id.value,
  }).then((res) => {
    treeData.value = res.data;
  });
};

onMounted(() => {
  getList();
});

const AssociatedPlatformRef = ref();
// 关联平台分类
const handleAssociatedPlatform = (data) => {
  AssociatedPlatformRef.value.open(data, "add");
};
</script>

<style lang="scss" scoped>
.filter {
  padding: 18px 0;
  margin-right: 10px;

  .title {
    margin: 0 0 15px;
    font-size: 18px;
    font-weight: bold;
    color: var(--el-color-info-dark-2);
    letter-spacing: 0.5px;
  }
  .content {
    :deep(.el-tree) {
      overflow-y: auto;

      .el-tree-node__content {
        height: 44px;
        display: flex;
        justify-content: flex-start;
      }
    }

    :deep(.el-tree--highlight-current) {
      .el-tree-node.is-current > .el-tree-node__content {
        background-color: var(--el-color-primary);
        width: 100%;

        .el-tree-node__label,
        .el-tree-node__expand-icon {
          color: white;
        }

        .is-leaf {
          color: transparent;
        }
      }
    }
  }

  .custom-tree-node {
    display: flex;
    justify-content: space-between;
    flex: 1;

    .tree-label {
      line-height: 32px;
      flex: 1;
      overflow: auto;
    }

    .tree-btn {
      width: 100px;
    }
  }
}

.content {
  overflow: auto;
  height: calc(100vh - 220px);
  padding-bottom: 20px;
}
.card svg:focus {
  outline: none;
}
.form-divider {
  .el-button {
    height: 28px;
  }
  .el-button + .el-button {
    margin-left: 8px;
  }
}
</style>
